package com.lse_api.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.StrictHttpFirewall;

/**
 * spring security config
 *
 * @author 祁雪
 */
@Configuration
@EnableWebSecurity
// 开启注解权限控制
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    /**
     * web.ignoring().anyRequest() 表示放通全部请求且这些请求不会经过spring security 过滤器
     *
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().anyRequest();
        web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
    }

    /**
     * http.authorizeRequests().anyRequest().permitAll() 表示全部请求不做权限判定 但全部需要经过spring security 过滤器
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // 权限验证
        http.authorizeRequests().antMatchers("/lseapi/backapi/**").authenticated();

        // 放通其他无权限接口
//        http.authorizeRequests().anyRequest().permitAll();

        // 自定义消息拒绝
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler());

        // 清除缓存
        http.headers().cacheControl();

    }

    @Bean
    public AccessDeniedHandler accessDeniedHandler() {
        return new CustomAccessDeniedHandler();
    }

    /**
     * 允许spring security 放行 带有 // 的请求
     *
     * @return
     */
    @Bean
    public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
        StrictHttpFirewall firewall = new StrictHttpFirewall();
        firewall.setAllowUrlEncodedDoubleSlash(true);
        return firewall;

    }
}
